<?php

namespace app\admin\model;

use ba\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

/**
 * User 模型
 * @controllerUrl 'userUser'
 * @property int id
 * @property int pid
 * @property int pay_count
 * @property number pay_money
 * @property number money
 * @property string username
 * @property string routine_openid
 * @property string unionid
 * @property string nickname
 * @property string mobile
 * @property string avatar
 * @property string gender
 * @property string lastlogintime
 * @property string lastloginip
 * @property string joinip
 * @property string jointime
 * @property string password
 * @property string salt
 * @property string status
 * @property int group_id
 */
class User extends Model
{
    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function getMoneyAttr($value): ?string
    {
        return bcdiv($value, 100, 2);
    }

    public function setMoneyAttr($value): string
    {
        return bcmul($value, 100, 2);
    }

    /**
     * 重置用户密码
     * @param int $uid 用户ID
     * @param string $newPassword 新密码
     * @return User
     */
    public function resetPassword(int $uid, string $newPassword): User
    {
        $salt = Random::build('alnum', 16);
        $passwd = encrypt_password($newPassword, $salt);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd, 'salt' => $salt]);
        return $ret;
        return $this->where(['id' => $uid])->update(['password' => $passwd, 'salt' => $salt]);
    }

    public function group()
    {
        return $this->belongsTo(UserGroup::class, 'group_id');
    }

    /**
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getParentTree($id): array
    {
        $tree = [];
        if ($id <= 0) return $tree;
        for ($i = 0; $i < 3; $i++) {
            $user = $this->where('id', $id)->find();
            $tree[] = $user;
            if ($user && $user->pid) {
                $id = $user->pid;
            } else {
                break;
            }
        }
        return $tree;
    }

    public function upgrade($id)
    {
        $oil = OilOrder::where(['user_id' => $id])->where('pay_time', '>', 0)->sum('pay_price');
        $goods = Order::where(['user_id' => $id])->where('pay_time', '>', 0)->sum('pay_price');
        $level = UserCard::where('condition', '<=', $oil + $goods)->order('condition desc, weight desc, id desc')->find();
        if (isset($level) && $level && isset($level['id'])) {
            $this->where('id', $id)->save(['level' => $level['id']]);
        }
    }
}